//
//  Data+extension.swift
//  iUtil
//
//  Created by wendachuan on 2019/7/22.
//  Copyright © 2019 wendachuan. All rights reserved.
//

import UIKit

public extension Data {
    
    /// 获得Int值
    ///
    /// - Returns: nil或者Int值
    /// - Throws: DataConvertError
    func intValue(encoding: String.Encoding = String.Encoding.utf8) throws -> Int {
        guard let strValue = String.init(data: self, encoding: encoding) else {
            throw NSError.init(errorCode: -1, errorDescription: "Can not convert data to string using encoding: [\(encoding)].")
        }
        guard let intValue = Int.init(strValue) else {
            throw NSError.init(errorCode: -2, errorDescription: "Can not convert string: [\(strValue)] to Int.")
        }
        return intValue
    }
    
    /// 获得Int64值
    ///
    /// - Returns: nil或者Int64值
    /// - Throws: DataConvertError
    func int64Value(encoding: String.Encoding = String.Encoding.utf8) throws -> Int64 {
        guard let strValue = String.init(data: self, encoding: encoding) else {
            throw NSError.init(errorCode: -1, errorDescription: "Can not convert data to string using encoding: [\(encoding)].")
        }
        guard let intValue = Int64.init(strValue) else {
            throw NSError.init(errorCode: -2, errorDescription: "Can not convert string: [\(strValue)] to Int64.")
        }
        return intValue
    }
    
    /// 获得Float值
    ///
    /// - Returns: nil或者Float值
    /// - Throws: DataConvertError
    func floatValue(encoding: String.Encoding = String.Encoding.utf8) throws -> Float {
        guard let strValue = String.init(data: self, encoding: encoding) else {
            throw NSError.init(errorCode: -1, errorDescription: "Can not convert data to string using encoding: [\(encoding)].")
        }
        guard let floatValue = Float.init(strValue) else {
            throw NSError.init(errorCode: -2, errorDescription: "Can not convert string: [\(strValue)] to Float.")
        }
        return floatValue
    }
    
    /// 获得Double值
    ///
    /// - Returns: nil或者Double值
    /// - Throws: DataConvertError
    func doubleValue(encoding: String.Encoding = String.Encoding.utf8) throws -> Double {
        guard let strValue = String.init(data: self, encoding: encoding) else {
            throw NSError.init(errorCode: -1, errorDescription: "Can not convert data to string using encoding: [\(encoding)].")
        }
        guard let doubleValue = Double.init(strValue) else {
            throw NSError.init(errorCode: -2, errorDescription: "Can not convert string: [\(strValue)] to Double.")
        }
        return doubleValue
    }
}
